package com.jeady.timetodo.activities

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.jeady.jxcompose.ButtonText
import com.jeady.jxcompose.ServerManager
import com.jeady.timetodo.R
import com.jeady.timetodo.activities.light.LightControlActivity
import com.jeady.timetodo.activities.light.VibrateActivity
import com.jeady.timetodo.activities.lock.LockActivity
import com.jeady.timetodo.activities.setting.SettingActivity
import com.jeady.timetodo.activities.task.TaskActivity
import com.jeady.timetodo.base.setClipboard
import com.jeady.timetodo.base.showToast
import com.jeady.timetodo.manager.Authentication
import com.jeady.timetodo.manager.Authentication.PinManager
import com.jeady.timetodo.manager.initNotification
import com.jeady.timetodo.services.updateRunningService
import com.jeady.timetodo.ui.theme.TimeToDoTheme

var unlocked by mutableStateOf(true)
class MainActivity : ComponentActivity() {
    private val TAG = "[MainActivity]"
    private lateinit var preference: SharedPreferences
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initNotification(this)
        preference = getSharedPreferences("timeToDo", MODE_PRIVATE)
        updateRunningService(applicationContext)
        val needUnlock = preference.getBoolean("needUnlock", true)
        if(needUnlock) unlocked = false
        setContent {
            TimeToDoTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize()
                ) {
                    Box(contentAlignment = Alignment.Center){
                        if(unlocked){
                            MainMenu()
                        }else{
                            LockedScreen()
                        }
                    }
                }
            }
        }
    }
    @Composable
    private fun MainMenu() {
        val context = LocalContext.current
        val menus = remember{ listOf(
            MenuInfo("定时控灯", activity = LightControlActivity::class.java),
            MenuInfo("定时锁屏", activity = LockActivity::class.java),
            MenuInfo("定时震动", activity = VibrateActivity::class.java),
//            MenuInfo("计划打卡", activity = AccountActivity::class.java),
            MenuInfo("任务列表", activity = TaskActivity::class.java),
            MenuInfo("APP设置", activity = SettingActivity::class.java),
            MenuInfo("立即\n锁定", colors = ColorTheme(Color(0xff50f0a0), Color(0xffa03030)), action={
                unlocked = false
                showToast(context, "App已锁定")
            }),
            MenuInfo("更多功能", activity = FutureActivity::class.java, action = {
                showToast(context, "敬请期待")
            })
        ) }
        LazyVerticalGrid(GridCells.Fixed(2),
            contentPadding= PaddingValues(10.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp),
            horizontalArrangement = Arrangement.spacedBy(10.dp)
        ){
            items(menus){info->
                Card(
                    Modifier
                        .height(200.dp)
                        .clickable {
                            info.activity?.let {
                                context.startActivity(Intent(context, it))
                            }
                            info.action?.invoke()
                        }
                ){
                    Box(
                        Modifier
                            .fillMaxSize()
                            .background(
                                info.colors?.bgColor ?: MaterialTheme.colorScheme.primaryContainer
                            ),
                        contentAlignment = Alignment.Center
                    ){
                        Text(info.name, color = info.colors?.color?:MaterialTheme.colorScheme.primary)
                    }
                }
            }
        }
    }
    @Composable
    fun LockedScreen(){
        val context = LocalContext.current
        var pinInput by remember{ mutableStateOf(false) }
        val pinStored = remember{ preference.getString("appPinCode", "")?:"" }
        val useSystemUnlock = remember{ preference.getBoolean("useSystemUnlock", false) }
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(20.dp)
        ) {
            Image(painterResource(R.drawable.icon), "图标",
                Modifier
                    .size(100.dp)
                    .clip(CircleShape))
            Text("APP已锁定", fontSize = 30.sp)
            if(useSystemUnlock) {
                ButtonText("系统身份验证", Modifier.fillMaxWidth()) {
Authentication.finger(context, mainExecutor) {
    unlocked = it
    showToast(context, if (it) "验证通过" else "验证失败")
}
                }
            }
            if(pinStored.isNotEmpty()) {
                ButtonText("应用PIN码解锁", Modifier.fillMaxWidth()) {
                    pinInput = true
                }
            }
            var showEmergencyInput by remember {
                mutableStateOf(false)
            }
            Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
                var emergencyCode by remember { mutableStateOf("") }
                var serverCode by remember {
                    mutableStateOf("123")
                }
                if(showEmergencyInput) {
                    OutlinedTextField(
                        value = emergencyCode,
                        onValueChange = { emergencyCode = it },
                        Modifier.fillMaxWidth(0.8f),
                        label = {
                            Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
                                Row {
                                    Text("公众号", color = Color.Gray)
                                    Text("《微代码人生》", Modifier.clickable {
                                        setClipboard(context, "微代码人生")
                                    },color = Color.Blue)
                                    Text("发送", color = Color.Gray)
                                    Text("'ecode-timetodo'", Modifier.clickable {
                                        setClipboard(context, "ecode-timetodo")
                                    }, color = Color.Blue)
                                }
                                Text("获取解锁码", color = Color.Gray)
                            }
                        },
                        singleLine = true,
                        textStyle = TextStyle(textAlign = TextAlign.Center)
                    )

                    LaunchedEffect(context) {
                        val serverManager = ServerManager.getInstance("http://gpt.zhncc.cn", 60)
                        serverManager.get(
                            "api/ecode",
                            "app=timetodo",
                            String::class.java
                        ) { res, err ->
                            serverCode = res ?: ""
                        }
                    }
                }
                ButtonText("紧急解锁") {
                    if(showEmergencyInput) {
                        if (emergencyCode.isBlank()) {
                            showToast(context, "请输入解锁码")
                        } else {
                            if (emergencyCode == "55666") {
                                unlocked = true
                                showToast(context, "会员解锁")
                            } else if (emergencyCode == serverCode) {
                                unlocked = true
                                showToast(context, "VIP解锁成功")
                            } else {
                                showToast(context, "解锁码错误")
                            }
                        }
                    }else{
                        showEmergencyInput = true
                    }
                }
            }
        }
        if(pinInput){
            if(pinStored.isNotEmpty()) {
                PinManager {
                    val verified = it == pinStored
                    showToast(context, if (verified) "验证通过" else "验证失败")
                    pinInput = false
                    if(verified) unlocked = true
                }
            }else{
                showToast(context, "未设置")
                pinInput = false
            }
        }
    }
    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart: ")
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume: ")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause: ")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "onStop: ")
    }
    override fun onDestroy() {
        Log.d(TAG, "onDestroy: ")
        super.onDestroy()
//        updateRunningService(this)
//        stopRunningService(baseContext)
    }
}

private data class MenuInfo(val name: String,
                            val icon: Painter?=null,
                            val colors: ColorTheme?=null,
                            val activity: Class<*>?=null,
                            val action: (()->Unit)?=null
)
private data class ColorTheme(val color: Color?=null, val bgColor: Color?=null)